﻿namespace SubhadraSolutions.Sharp.Utils.Threading
{
    using SubhadraSolutions.Sharp.Utils.Collections.Concurrent;

    /// <summary>
    /// The AbstractFlyweightBasedDispatcherProvider class.
    /// </summary>
    public abstract class AbstractFlyweightBasedDispatcherProvider : IDispatcherProvider
    {
        /// <summary>
        /// The flyweight
        /// </summary>
        private readonly GenericFlyweight<IDispatcher> flyweight;

        /// <summary>
        /// Initializes a new instance of the <see cref="AbstractFlyweightBasedDispatcherProvider"/> class.
        /// </summary>
        /// <param name="useWeakReferences">if set to <c>true</c> [use weak references].</param>
        protected AbstractFlyweightBasedDispatcherProvider(bool useWeakReferences)
        {
            this.flyweight = new GenericFlyweight<IDispatcher>(this.GetDispatcherCore, useWeakReferences);
        }

        /// <summary>
        /// Gets the dispatcher core.
        /// </summary>
        /// <param name="target">The target.</param>
        /// <returns></returns>
        protected abstract IDispatcher GetDispatcherCore(object target);

        /// <summary>
        /// Gets the dispatcher.
        /// </summary>
        /// <param name="target">The target.</param>
        /// <returns></returns>
        public IDispatcher GetDispatcher(object target)
        {
            return this.flyweight.GetObject(target);
        }
    }
}
